//
//  HostAttentionViewController.m
//  SuperRadio
//
//  Created by Damon on 14/12/17.
//  Copyright (c) 2014年 三个臭皮匠. All rights reserved.
//

#import "HostAttentionViewController.h"
#import "HostAttentionDetail.h"
#import "HostAttentionCell.h"
#import "NetHandler.h"
#import "Introduction.h"
#import "HostViewController.h"

#import "UIScrollView+MJRefresh.h"
#import "UIScrollView+Extension.h"

@interface HostAttentionViewController ()<UITableViewDataSource, UITableViewDelegate>

@property(nonatomic, retain) NSMutableArray *arr;

@property(nonatomic, retain) UITableView *attentionTableView;


// 当前的请求页数
@property (nonatomic, assign) NSInteger pageId;
// 最大得页数
@property (nonatomic, assign) NSInteger maxPageId;

@end

@implementation HostAttentionViewController

#pragma mark 初始化
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        self.pageId = 1;
        
        self.arr = [NSMutableArray array];
    }
    return self;
}

#pragma mark 数据处理
- (void)handleData
{
     NSString *pageId = [NSString stringWithFormat:@"%ld", self.pageId];
    
    NSString *str = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/others/following?device=iPhone&pageId=%@&pageSize=30&toUid=%@", pageId, self.introduction.uid];
    
    [NetHandler getDataWithURL:str completion:^(NSData *data) {
        
        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        self.pageId = [[result objectForKey:@"pageId"] integerValue];
        self.maxPageId = [[result objectForKey:@"maxPageId"] integerValue];

        
        NSMutableArray *array = [result objectForKey:@"list"];
        
        for (NSDictionary *dic in array) {
            HostAttentionDetail *hostAtt = [[HostAttentionDetail alloc] initWithDictionary:dic];
            [self.arr addObject:hostAtt];
            [hostAtt release];
        }
        
        if (self.arr.count == 0) {
            UIImageView *attenImage = [[UIImageView alloc] initWithFrame:self.view.frame];
            attenImage.image = [UIImage imageNamed:@"back4.jpg"];
            [self.view addSubview:attenImage];
            [attenImage release];
        }
        
        [self.attentionTableView reloadData];
    }];
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self handleData];
    self.title = @"关注";
    // Do any additional setup after loading the view.
    
    self.attentionTableView = [[UITableView alloc] initWithFrame:CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    self.attentionTableView.dataSource = self;
    self.attentionTableView.delegate = self;
    
    [self.view addSubview:self.attentionTableView];
    
    [_attentionTableView release];
    
    [self.attentionTableView registerClass:[HostAttentionCell class] forCellReuseIdentifier:@"attention"];
    
    [self setupRefresh];
}


- (void)setupRefresh
{
    //    NSLog(@"进入了setupRefresh");
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    
    //    [self.detailsTableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    //    //进入刷新状态(一进入程序就下拉刷新)
    //    [self.detailsTableView headerBeginRefreshing];
    
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.attentionTableView addFooterWithTarget:self action:@selector(footerRereshing)];
}



#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    
    //1. 在这调用请求网络数据方法（刷新数据）
    
    //2. 2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.attentionTableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.attentionTableView headerEndRefreshing];
    });
}

//   进入加载状态
- (void)footerRereshing
{
    //1. 拼接口等操作
    // 请求加载数据
    
    // 如果是音频列表
    
    // 小于最大页码
    if (self.pageId < self.maxPageId) {
        // 页码加1
        ++self.pageId;
        
        
        NSString *pageId = [NSString stringWithFormat:@"%ld", self.pageId];
        
        NSString *str = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/others/following?device=iPhone&pageId=%@&pageSize=30&toUid=%@", pageId, self.introduction.uid];
        
        [NetHandler getDataWithURL:str completion:^(NSData *data) {
            
            id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            

            NSMutableArray *array = [result objectForKey:@"list"];
            
            for (NSDictionary *dic in array) {
                HostAttentionDetail *hostAtt = [[HostAttentionDetail alloc] initWithDictionary:dic];
                [self.arr addObject:hostAtt];
                [hostAtt release];
            }
            
            [self.attentionTableView reloadData];
        }];

        
        
        
        
    }
    
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.attentionTableView reloadData];
        [self.attentionTableView footerEndRefreshing];
    });
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arr.count;
}

#pragma mark cell设置
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HostAttentionCell *cell = [tableView dequeueReusableCellWithIdentifier:@"attention"];
    HostAttentionDetail *attention = [self.arr objectAtIndex:indexPath.row];
    cell.hostAttention = attention;
    
    return cell;
}

#pragma mark 点击cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    HostViewController *hostVC = [[HostViewController alloc] init];
    
    hostVC.introduction.uid = [[self.arr objectAtIndex:indexPath.row] uid];
   // NSLog(@"%@", [[self.arr objectAtIndex:indexPath.row] uid]);
    [self.navigationController pushViewController:hostVC animated:YES];
    [hostVC release];
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}


- (void)dealloc
{
    [_attentionTableView release];
    [_arr release];
    
    [super dealloc];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
